package org.thraex.pms.question.action;

import com.google.gson.Gson;
import lombok.extern.java.Log;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author 鬼王
 * @Date 2019/08/23 13:48
 */
@Log
public class AccountAction extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        log.info(">>>>>>>>>>>>>>>>>> Execute #doGet(HttpServletRequest req, HttpServletResponse resp)");
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        log.info(">>>>>>>>>>>>>>>>>> Execute #doPost(HttpServletRequest req, HttpServletResponse resp)");

        resp.setContentType("application/json;charset=UTF-8");

        ServletOutputStream os = resp.getOutputStream();

        // java.lang.IllegalStateException: getOutputStream() has already been called for this response
        PrintWriter writer = resp.getWriter();

        Map<String, String> account = new HashMap<>(3);
        account.put("id", "O70");
        account.put("name", "Guiwang");
        //account.put("nickname", "鬼王");
        account.put("email", "THRAEX@aliyun.com");

        Map<String, String> headers = new HashMap<>();
        Enumeration headerNames = req.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String hn = headerNames.nextElement().toString();
            headers.put(hn, req.getHeader(hn));
        }

        Map<String, Object> result = new HashMap<>(2);
        result.put("account", account);
        result.put("headers", headers);

        os.write(new Gson().toJson(result).getBytes());
        //os.flush();
        //os.close();

        //resp.getWriter().write(new Gson().toJson(result));
        //resp.getWriter().flush();
        //resp.getWriter().close();
    }
}
